package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.dto.InitExplainDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.service.toolbox.help.UpdatePackageRedisService;
import com.xbongbong.sys.domain.entity.CompanyEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.CompanyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2020/08/28 14:09
 */

@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/package")
public class PackageScriptController {

    public static final Logger LOGGER = LoggerFactory.getLogger(PackageScriptController.class);

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private CompanyModel companyModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private UpdatePackageRedisService updatePackageRedisService;
    @Resource
    private CompanyConfigModel companyConfigModel;

    @RequestMapping(value = "/validateFeature", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String validateFeature(@RequestBody @Valid InitExplainDTO initExplainDTO) throws XbbException {
        if (!proBaseConfig.getXbbCode().equals(initExplainDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
        }
        long startTime = DateTimeUtil.getLong();
        //获取未删除的公司数量
        Set<String> corpidSet = new HashSet<>();
        Map<String, Object> companyParam = new HashMap<>(1);
        companyParam.put("del", BasicConstant.ZERO);
        companyParam.put("status", 1);
        companyParam.put("vipNumGte", 0);
        long now = DateTimeUtil.getTodayInt();
        companyParam.put("feeEndTimeGte", now);
        Integer companyCount = companyModel.getEntitysCount(companyParam);

        Integer pageSize = 500;
        for (int i = 0; i <= companyCount; i += pageSize) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("del", BasicConstant.ZERO);
            param.put("pageNum", pageSize);
            param.put("start", i);
            param.put("status", 1);
            param.put("columns", "corpid");
            param.put("vipNumGte", 0);
            param.put("feeEndTimeGte", now);
            List<CompanyEntity> companyList = companyModel.findEntitys(param);
            for (CompanyEntity item : companyList) {
                String corpid = item.getCorpid();
                for (ValueAddedTypeEnum valueAddedTypeEnum: ValueAddedTypeEnum.getValueAddedType()) {
                    Integer num = updatePackageRedisService.getOverNum(corpid, valueAddedTypeEnum);
                    if (num > 0) {
                        corpidSet.add(corpid);
                        break;
                    }
                }
            }
            LOGGER.info("执行到第" + i +"条，"+"共" + companyCount + "条");
        }
        String corpidString = JSON.toJSONString(corpidSet);
        LOGGER.info("白名单中的公司："+ corpidString);

        if (CollectionsUtil.isNotEmpty(corpidSet)) {
            companyConfigModel.save(PaasConstant.DEFAULT_DATA_CORPID, CompanyConfigEnum.PACKAGE_WHITELIST.getAlias(), CompanyConfigEnum.PACKAGE_WHITELIST.getName(), corpidString);
            paasRedisHelper.setValue4Set(RedisConstant.KEY_COMPANY_CONFIG, CompanyConfigEnum.PACKAGE_WHITELIST.getAlias(), corpidSet, TimeConstant.SECONDS_PER_HOUR);

        }
        LOGGER.info("总公司数量："+ companyCount);
        long endTime = DateTimeUtil.getLong();
        long time = endTime - startTime;
        LOGGER.info("花费时间：" + time);
        JSONObject object = new JSONObject();
        object.put("success", "成功");
        return object.toJSONString();

    }

}
